package com.scalar.chiptrack.workflow;

import java.awt.BorderLayout;
import java.awt.Component;
import java.io.ByteArrayOutputStream;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;


public class XPDLPreview extends JPanel{
	
	private Editor editor;

	private JScrollPane xpdlScrollPane;
	private JTextArea xpdlTextArea;
		
	public XPDLPreview(Editor editor){
		this.editor = editor;
		setBorder(BorderFactory.createEtchedBorder());
		setLayout(new BorderLayout());
		add(createCenterComponent(), BorderLayout.CENTER);
	}
	
	public Component createCenterComponent(){
		xpdlTextArea = new JTextArea();
		xpdlTextArea.setLineWrap(false);
		xpdlTextArea.setEditable(false);
		xpdlTextArea.setWrapStyleWord(false);
		
		xpdlScrollPane = new JScrollPane();
		xpdlScrollPane.setViewportView(xpdlTextArea);
		JViewport port= xpdlScrollPane.getViewport();
		port.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
		
		return xpdlScrollPane;
	}
	
	public void refreshView(WorkflowModel model){
		try{
			
			Document document = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dbf.newDocumentBuilder();
			
			document = builder.newDocument();
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			editor.getGraph().getWorkflowManager().toXML(document, null, null, null);
			
			TransformerFactory tFactory = TransformerFactory.newInstance();
         	Transformer transformer = tFactory.newTransformer();
         	transformer.setOutputProperty("indent","yes");
         	transformer.setOutputProperty("{https://xml.apache.org/xslt}indent-amount","4");
         	transformer.setOutputProperty("encoding","UTF-8");
         
         	DOMSource source = new DOMSource(document);
         	StreamResult result = new StreamResult(baos);
         	transformer.transform(source,result);

         	xpdlTextArea.setText(baos.toString("UTF8"));
         	
         	baos.close();
         	
         	//xpdlTextArea.setText(model.displayCells());
         	
		}catch(Exception ex){
			ex.printStackTrace();
			xpdlTextArea.setText("");
		}
	}
	
}